package com.lzy.crm.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lzy.crm.base.page.PageQuery;
import com.lzy.crm.base.util.BootStrapReturn;
import com.lzy.crm.base.util.JsonUtil;
import com.lzy.crm.base.util.StringUtil;
import com.lzy.crm.domain.CardFlow;
import com.lzy.crm.domain.Dict;
import com.lzy.crm.domain.PpUser;
import com.lzy.crm.domain.User;
import com.lzy.crm.service.CardFlowService;
import com.lzy.crm.service.DictService;
import com.lzy.crm.service.UserService;
import com.lzy.crm.util.BootJsonResponse;
import com.lzy.crm.util.UserConstants;
import com.lzy.crm.vo.CardFlowVo;
import com.lzy.crm.vo.PlayerInfo;


/**
 * 饭卡控制器
 * @author chenshiping
 *
 */
@Controller
@RequestMapping("/admin2")
public class CardFlowController {
	
	Logger logger= Logger.getLogger(CardFlowController.class);
	
	
	@Resource
	private CardFlowService cardFlowService;
	
	@Resource
	private UserService userService;
	
	@Resource
	DictService dictService;
	
	/**
	 * 玩家充饭卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_list")  
	public String roomCard(HttpServletRequest request,ModelMap model) {
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			PlayerInfo playerInfo=userService.getPlayerInfo(user.getGameUserId(), null);
			model.put("totalCard", playerInfo.getInsureScore());
		} catch (Exception e) {
			logger.error("饭卡列表 ", e);
		}
		return "card/card_index";
	}
	
	
	/**
	 * 饭卡流入
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_list_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String roomCardData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<PlayerInfo> result = new BootStrapReturn<PlayerInfo>();
		try {
			String gameId= request.getParameter("gameId");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			List<PlayerInfo> playerInfoList=  userService.getPlayerInfoList(gameId);
			result.setPage(1);
			result.setTotal(playerInfoList.size());
			result.setRows(playerInfoList);
		} catch (Exception e) {
			logger.error("获取方法json 方法", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	@RequestMapping(path="/card_query_user",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String cardUserInfo(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		try {
			String userId= request.getParameter("userId");
			List<PlayerInfo> playerInfoList=  userService.getPlayerInfoList(userId);
			if(playerInfoList!=null&&playerInfoList.size()>0){
				model.put("statusCode", "200");
				model.put("playerName", playerInfoList.get(0).getNickName());
			}else{
				model.put("playerName", "未查到玩家信息");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return JsonUtil.toJson(model) ;
	}
	
	
	/**
	 * 查询当个玩家信息
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_add")  
	public String cardAdd(HttpServletRequest request,ModelMap model) {
		try {
			Integer gameId =Integer.parseInt(request.getParameter("gameId"));
			PlayerInfo playerInfo= userService.getPlayerInfo(gameId,null);
			model.put("playerInfo", playerInfo);
		} catch (Exception e) {
			logger.error("到添加页面", e);
		}
		return "card/card_add";
	}
	/**
	 * 给玩家添加房卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_add_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String cardSave(HttpServletRequest request, 
			ModelMap model) {
		BootJsonResponse response=new BootJsonResponse();
		try{
			Integer gameId = Integer.parseInt(request.getParameter("gameId")); // 玩家ID
			Integer userId = Integer.parseInt(request.getParameter("userId")); // 玩家ID
			Integer function = Integer.parseInt( request.getParameter("func"));  			 // 玩家购买的套餐
			Integer card = Integer.parseInt(request.getParameter("card"));  			 // 玩家购买的卡数
			Integer awardCard = Integer.parseInt(request.getParameter("awardCard"));    //赠玩家的卡数
			String remark = request.getParameter("remark");  		 //备注
			String buyCardGroupId = request.getParameter("buyCardGroupId"); 
			if(StringUtil.equals("1", buyCardGroupId)){
				// 套餐购买方案
				if(1== function){
					card = 1; awardCard=0;
				}else if(13==function){
					card = 12; awardCard=1;
				}else if(40== function){
					card = 36; awardCard=4;
				}else if(90 == function){
					card = 80; awardCard=10;
				}else if(180 ==function){
					card = 160; awardCard=20;
				} 
			}else{
				function=null;
			}
			if(userId==null||card==null||(0<=card&&10000<card)||(0<=awardCard&&10000<awardCard)){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("请填写正确的购买信息");
				return JsonUtil.toJson(response) ;
			}else{
				
					PlayerInfo playerInfo=new PlayerInfo();// 组装信息
					playerInfo.setGameId(gameId);
					playerInfo.setUserId(userId);
					playerInfo.setCard(card);
					playerInfo.setAwardCard(awardCard);
					playerInfo.setFunc(function);
					playerInfo.setRemark(remark);
					User user = (User)request.getSession().getAttribute("userSession");
					String result = "";
					// 代理商添加房卡
					result = cardFlowService.newBuyCard(playerInfo, user);
					if(StringUtil.equals("01", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
						response.setMessage("充卡成功");
					}else if(StringUtil.equals("03", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("代理商信息有误，请联系管理员");
					}else if(StringUtil.equals("04", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("玩家信息有误，请联系管理员");
					}else if(StringUtil.equals("02", result)){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("房卡不足，请先充值房卡");
					}
			}
		}catch(Exception e){
			logger.error("给玩家充值房卡失败", e);
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("系统错误，请联系管理员");
			return JsonUtil.toJson(response) ;
		}
		return JsonUtil.toJson(response) ;
	}
	
	
	
	
	
	
	/**
	 * 饭卡流出
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_inflow")  
	public String roomCardInflow(HttpServletRequest request,ModelMap model) {
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			User userInfo = userService.getById(user.getId());
			userInfo.setPassword(null);
			model.put("userInfo", userInfo);
		} catch (Exception e) {
			logger.error("饭卡流出", e);
		}
		return "card/card_inflow";
	}
	/**
	 * 饭卡流出
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_inflow_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String cardInflowData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<CardFlow> result = new BootStrapReturn<CardFlow>();
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			String bId = request.getParameter("bId");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			List<CardFlow> cardFlowList  = cardFlowService.getCardFlowList(user.getGameUserId().toString(), bId,pageQuery);
			for (CardFlow cardFlow : cardFlowList) {  // 充值数据 等于购买金额 + 赠送金额
				cardFlow.setCard(cardFlow.getCard()+cardFlow.getAwardCard());
			}
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(cardFlowList);
		} catch (Exception e) {
			logger.error("饭卡流出查询", e);
		}
		return JsonUtil.toJson(result) ;
	}
	
	
	
	
	
	
	
	/**
	 * 饭卡流入
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_into")  
	public String roomCardInto(HttpServletRequest request,ModelMap model) {
		return "card/card_into";
	}
	
	/**
	 * 饭卡流入
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_into_data",method=RequestMethod.POST,produces="text/html;charset=UTF-8") 
	@ResponseBody
	public String roomCardIntoData(HttpServletRequest request, @RequestParam Map<String, String> form,
			ModelMap model) {
		BootStrapReturn<CardFlowVo> result = new BootStrapReturn<CardFlowVo>();
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			Integer currentPage = Integer.parseInt(request.getParameter("numPerPage"));
			Integer numPerPage = Integer.parseInt(request.getParameter("pageNum"));
			PageQuery pageQuery = new PageQuery(numPerPage,currentPage);
			pageQuery.setIsQueryTotal(true); 
			List<CardFlowVo> cardFlowVoList  = cardFlowService.getCardFlowVoList(null,user.getGameUserId().toString(),pageQuery);
			result.setPage(pageQuery.getPageIndex());
			result.setTotal(pageQuery.getTotalCount());
			result.setRows(cardFlowVoList);
		} catch (Exception e) {
			logger.error("饭卡流入", e);
		}
		return JsonUtil.toJson(result) ;
	}

	
	/**
	 * 查询单个代理商信息
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_user_add")  
	public String cardUserAdd(HttpServletRequest request,ModelMap model) {
		try {
			Integer userId =Integer.parseInt(request.getParameter("userId"));
			User adduser = userService.getById(userId);
			adduser.setPassword(null);
			model.put("adduser", adduser);
			model.put("totalCard", 0);
			if(adduser.getGameUserId()!=null){
				PlayerInfo playerInfo=userService.getPlayerInfo(adduser.getGameUserId(), null);
				model.put("totalCard", playerInfo.getInsureScore());
			}
		} catch (Exception e) {
			logger.error("查询单个代理商信息", e);
		}
		return "card/card_user_add";
	}
	
	
	/**
	 * 给代理商添加房卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_user_add_save",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String cardUserSave(HttpServletRequest request, 
			ModelMap model){
		BootJsonResponse response=new BootJsonResponse();
		try{
			Integer gameId =Integer.parseInt(request.getParameter("gameId")); // 玩家ID
			Integer userId = Integer.parseInt(request.getParameter("userId")); // 玩家ID
			Integer function = Integer.parseInt(request.getParameter("func"));  			 // 玩家购买的套餐
			Integer card = Integer.parseInt(request.getParameter("card"));  			 // 玩家购买的卡数
			Integer awardCard = Integer.parseInt(request.getParameter("awardCard"));    //赠玩家的卡数
			String remark = request.getParameter("remark");  		 //备注
			String buyCardGroupId = request.getParameter("buyCardGroupId"); 
			Integer orMoney = Integer.valueOf(request.getParameter("orMoney"));
			if(StringUtil.equals("1", buyCardGroupId)){
				// 套餐购买方案
				if(1== function){
					card = 1; awardCard=0;
				}else if(13 == function){
					card = 12; awardCard=1;
				}else if(40== function){
					card = 36; awardCard=4;
				}else if(90 == function){
					card = 80; awardCard=10;
				}else if(180== function){
					card = 160; awardCard=20;
				} 
			}else{
				function=null;
			}
			User user = (User)request.getSession().getAttribute("userSession");
			if(userId==null||card==null||(0<=card&&10000<card)||(0<=awardCard&&10000<awardCard)
					){
				response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
				response.setMessage("购买信息有误,请填写正确的购买信息");
				return JsonUtil.toJson(response) ;
			}else{
				
					PlayerInfo playerInfo=new PlayerInfo();// 组装信息
					playerInfo.setGameId(gameId);
					playerInfo.setUserId(userId);
					playerInfo.setCard(card);
					playerInfo.setAwardCard(awardCard);
					playerInfo.setFunc(function);
					playerInfo.setRemark(remark);
					String result=cardFlowService.buyAgentCard(playerInfo, user, orMoney);
					if(StringUtil.equals(result,"02")){
						response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
						response.setMessage("房卡不足，请先充值房卡 ");
					}
					response.setStatusCode(BootJsonResponse.STATUS_CODE_SUCCESS);
					response.setMessage("充卡成功");
			}
		}catch(Exception e){
			logger.error("给代理商充值房卡失败", e);
			response.setStatusCode(BootJsonResponse.STATUS_CODE_FAILURE);
			response.setMessage("系统错误，请联系管理员");
			return JsonUtil.toJson(response) ;
		}
		return JsonUtil.toJson(response) ;
	}
	
	
	
	
	
	
	/*********  手机兼容模块   ************/
	
	/**
	 * 手机兼容模块
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_menu_mobile")  
	public String mobileCard(HttpServletRequest request,ModelMap model) {
		try {
			PpUser user = (PpUser)request.getSession().getAttribute("userSession");
			
			
			
			/*if(StringUtil.equals(user.getUserType(), UserConstants.USER_TYPE_MANAGE)||
					(dictList!=null&&dictList.size()>0&&StringUtil.equals("1", dictList.get(0).getDictValue()) )){
				model.put("addCard", "1");
			}else{
				model.put("addCard", "2");
			}*/
			//model.put("userInfo", userInfo);
		} catch (Exception e) {
			logger.error("手机模块", e);
		}
		return "mobile/card/card_menu";
	}
	
	/**
	 * 充饭卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_add_mobile")  
	public String card_list_mobile(HttpServletRequest request,ModelMap model) {
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			PlayerInfo playerInfo=userService.getPlayerInfo(user.getGameUserId(), null);
			model.put("totalCard", playerInfo.getInsureScore());
		} catch (Exception e) {
			logger.error("去充饭卡页面", e);
		}
		return "mobile/card/card_index";
	}
	
	/**
	 * 充饭卡
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_add_agent_mobile")  
	public String card_add_agent_mobile(HttpServletRequest request,ModelMap model) {
		try {
			User user = (User)request.getSession().getAttribute("userSession");
			PlayerInfo playerInfo=userService.getPlayerInfo(user.getGameUserId(), null);
			model.put("totalCard", playerInfo.getInsureScore());
		} catch (Exception e) {
			logger.error("去充饭卡页面", e);
		}
		return "mobile/card/card_agent_index";
	}
	
	/**
	 * 查询当个玩家信息
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(path="/card_add_mobile",method=RequestMethod.POST,produces="text/html;charset=UTF-8")
	@ResponseBody
	public String card_add_mobile(HttpServletRequest request,ModelMap model) throws Exception{
		try{
			Integer gameId =Integer.parseInt(request.getParameter("gameId"));
			PlayerInfo playerInfo= userService.getPlayerInfo(gameId,null);
			if(playerInfo!=null){
				model.put("playerInfo", playerInfo);
			}
			model.put("statusCode", BootJsonResponse.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			logger.error("查询单个玩家错误", e);
			model.put("statusCode", BootJsonResponse.STATUS_CODE_FAILURE);
		}
		return JsonUtil.toJson(model);
	}
	
	/**
	 * 饭卡流入
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_into_mobile")  
	public String roomCardIntoMobile(HttpServletRequest request,ModelMap model){
		return "mobile/card/card_into";
	}
	
	/**
	 * 饭卡流出
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_inflow_mobile")  
	public String roomCardInflowMobile(HttpServletRequest request,ModelMap model){
		return "mobile/card/card_inflow";
	}
		
	/**
	 * 查询单个代理商信息
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/card_user_add_mobile")  
	public String cardUserAddMobile(HttpServletRequest request,ModelMap model) {
		try {
			Integer userId =Integer.parseInt(request.getParameter("userId"));
			User adduser = userService.getById(userId);
			adduser.setPassword(null);
			model.put("adduser", adduser);
			model.put("totalCard", 0);
			if(adduser.getGameUserId()!=null){
				PlayerInfo playerInfo=userService.getPlayerInfo(adduser.getGameUserId(), null);
				model.put("totalCard", playerInfo.getInsureScore());
			}
		} catch (Exception e) {
			logger.error("饭卡流出", e);
		}
		return "mobile/card/card_user_add";
	}
	
}
